package com.youku.component.procedure;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.math.NumberUtils;

import com.youku.component.BaseAttribute;
import com.youku.component.TestCase;
import com.youku.component.result.ExecuteResult;
import com.youku.expression.Expression;
import com.youku.expression.Position;

public abstract class AbstractProcedure implements Procedure {

	protected Expression times;

	protected TestCase testCase;

	protected String id;

	protected List<ExecuteResult> results = new ArrayList<>();

	public AbstractProcedure() {
		super();
	}

	public AbstractProcedure(String id, TestCase testCase, String times) {
		this.id = id;
		this.testCase = testCase;
		this.times = createExpression(times);
	}

	protected Expression createExpression(String valueString) {
		return new Expression(Position.create(testCase), valueString);
	}

	@Override
	public void run() {
		results.clear();
		int t = NumberUtils.toInt(times.get(), 1);
		for (int i = 0; i < t; i++) {
			invoke();
		}
	}

	public ExecuteResult getResult(int i) {
		return results.get(i - 1);
	}

	@Override
	public String getKey() {
		return id;
	}

	@Override
	public void updatePosition(Position position) {
		if(times!=null)
			times.setPosition(position);
	}

	@Override
	public void setScope(BaseAttribute attribute) {
		if(attribute instanceof TestCase){
			testCase=(TestCase) attribute;
		}else{
			throw new RuntimeException(attribute.getId()+"不是测试用例,这里需要一个测试用例");
		}
	}

}
